# -*- coding:utf-8 -*-

'''
PROJECT_NAME : websocket_schedule_with_flask
file    : views
author  : 1032162439@qq.com
date    : 2022-10-26 14:39
IDE     : PyCharm
'''
import uuid

from flask import render_template, request, redirect, url_for, flash, session, jsonify

from . import admin_bp
from app.models import User, Role, Status, Action, StatusTransfer, Item, ItemClass, WorkFlow
from app import db


@admin_bp.route('/test')
def admin_test():
    return 'test....'


@admin_bp.route('/create')
def create_item():
    order_id = str(uuid.uuid4())
    item = Item()
    item.order_id = order_id
    item.order_type = 1
    item.order_status = 2
    item.active_user = 1
    try:
        db.session.add(item)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
    return "创建成功"


@admin_bp.route('/items')
def item_list():
    obj = Item.query.all()[0]
    print(obj.order_type.item_cls_name)
    print(obj.order_status.status_name)
    print(obj.active_user.name)
    return 'items'


@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    name = request.form.get('username')
    password = request.form.get('password')
    user_obj = User.query.filter(User.name == name, User.password == password).first()
    if not user_obj:
        flash('用户名或者密码错误')
        return redirect(url_for('admin_bp.login'))
    session['login_user'] = {
        'id': user_obj.id,
        'name': user_obj.name,
        'role': user_obj.role.role_name
    }
    return redirect(url_for('admin_bp.index'))


@admin_bp.route('/')
def index():
    user_obj = session.get('login_user')
    if not user_obj:
        return redirect(url_for('admin_bp.login'))
    # 获取当前用户所有的工单列表
    item_list = Item.query.filter(Item.create_user_id == user_obj['id']).all()
    # 获取当前用户能够操作的工单
    require_action_list = Item.query.filter(Item.active_user_id == user_obj['id']).all()
    context = {
        'item_list': item_list,
        'require_action_list': require_action_list
    }
    return render_template('admin_bp/index.html', **context)


@admin_bp.route('/item/detail/<id>')
def item_detail(id):
    detail: Item = Item.query.filter(Item.order_id == id).order_by(Item.update_time.desc()).first()
    print(detail)
    context = {
        'order_id': detail.order_id,  # 工单编号
        'order_type': detail.order_type.item_cls_name,  # 工单类型 ： 请假
        'order_comments': detail.comments,  # 工单备注
        'order_status': detail.order_status.status_name,  # 工单状态
        'order_creator': detail.create_user.name,  # 工单创建者
        'order_create_time': detail.create_time  # 工单创建时间
    }
    return render_template('admin_bp/item_detail.html', **context)


@admin_bp.route('/action/submit')
def action_submit():
    status = {
        'code': 0,
        'msg': 'ok'
    }
    action = request.args.get('action')
    order_type = request.args.get('orderType')
    order_id = request.args.get('orderID')
    comments = request.args.get('comments')
    creator = request.args.get('creator')
    order_create_time = request.args.get('orderCreateTime')
    # 从人员列表中获取到creator
    user_obj = User.query.filter(User.name == creator).first()
    # 获取action 提交
    # 从状态转移表获取动作对应的当前状态和下一个状态
    action_obj = Action.query.filter(Action.action_name == action).first()
    status_transfer_obj = StatusTransfer.query.filter(StatusTransfer.action == action_obj).first()
    # 当前状态：已保存
    print(status_transfer_obj.current_status.status_name)
    # 下一个状态：待审批
    print(status_transfer_obj.next_status.status_name)
    # 从审批流表中获取到下一个操作者
    ## 1 先获取工单类型对象
    item_class_obj = ItemClass.query.filter(ItemClass.item_cls_name == order_type).first()
    ## 2 获取当前工单的状态
    status_obj = Status.query.filter(Status.status_name == status_transfer_obj.next_status.status_name).first()
    ## 3 获取工作流WorkFlow中下一个操作的人
    workflow_obj: WorkFlow = WorkFlow.query.filter(
        WorkFlow.order_status == status_obj,
        WorkFlow.order_type == item_class_obj,
    ).first()
    ## 4 新增一条记录，存储到Item中
    item_obj = Item()
    item_obj.order_id = order_id
    item_obj.order_type_id = item_class_obj.id
    item_obj.order_status_id = status_obj.id
    item_obj.active_user_id = workflow_obj.next_user_id
    item_obj.comments = comments
    item_obj.create_time = order_create_time
    item_obj.create_user_id = user_obj.id
    db.session.add(item_obj)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
    return jsonify(**status)


@admin_bp.route('/logout')
def logout():
    session.pop('login_user')
    return redirect(url_for('admin_bp.login'))


@admin_bp.route('/test_api')
def test_api():
    return jsonify(name='test_api')
